package com.test.daily.leetcode.y2022.m05.day0516.v01;

/**
 * @author Tom on 2022/5/16
 */
public class Solution {
    public static void main(String[] args) {

    }

    public class Heap {
        public int limit;
        public int heapSize;
        public int[] arr;

        public Heap(int limit) {
            this.limit = limit;
            this.heapSize = 0;
            this.arr = new int[limit];
        }

        public void swap(int[] arr, int i, int j) {
            int tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
        }

        public void push(int value) {
            if (heapSize >= limit) {
                throw new RuntimeException("is full!");
            }
            arr[heapSize] = value;
            heapInsert(arr, heapSize++);
        }

        public int pop() {
            int ans = arr[0];
            swap(arr, 0, --heapSize);
            heapify(arr, heapSize, 0);
            return ans;
        }

        public void heapInsert(int[] arr, int index) {
            while (arr[index] < arr[(index - 1) / 2]) {
                swap(arr, index, (index - 1) / 2);
                index = (index - 1) / 2;
            }
        }

        public void heapify(int[] arr, int heapSize, int index) {
            int left = index * 2 + 1;
            while (left < heapSize) {
                int largest = (left + 1) < heapSize && arr[left] < arr[left + 1] ? left + 1 : left;
                largest = arr[index] > arr[largest] ? index : largest;
                if (index == largest) {
                    break;
                }
                swap(arr, index, largest);
                index = largest;
                left = index * 2 + 1;
            }
        }
    }
}
